<?php

define('_LINK_TYPE_PLAIN',	1);
define('_LINK_TYPE_BUTTON',	2);

/**
 * ICE_HTML, HTML Utility Class
 *
 * @category   icestorm
 * @package    ICESTORM
 * @author     Magnus Jonsson <magnus.jonsson@codealliance.se>
 * @copyright  2008 Team babel
 * @license    LGPL
 */
class ICE_HTML
{

	/**
	* Refresh Page
	*
	* @access public
	* @param  string Frame to refresh
	* @param  string Page URL to refresh
	*/
	function refresh($frame,$href,$timer=0)
	{
		echo "<script langauage=\"JavaScript\">
			function Redirect() {
            	top.$frame.location.href='$href'
   			}";

		if ( $timeout > 0 )
		{
   	  		echo "window.setTimeout('Redirect();', $timer)";
		} else {
			echo 'Redirect();';
		}
		echo '</script>';
	}

	/**
	* Drop Down Listbox
	*
	* @access public
	* @param  array Mixed Select Tag Info
	* @param  boolean Echo defaults to false
	* @return string HTML Output
	*/
   function ddlb($array,$echo = false) {
      $output = '<select ';
      if (isset($array['extrahtml'])) {
         $output .= $array['extrahtml'].' ';
      }
      if (isset($array['id'])) $output.='id="'.$array['id'].'" ';
      if (isset($array['class'])) $output.='class="'.$array['class'].'" ';
      if (isset($array['style'])) $output.='style="'.$array['style'].'" ';
      if (isset($array['size'])) {
      	$output.='size="'.$array['size'].'" ';
      } else {
      	$output.='size="1" ';
      }
      $output.='name="'.$array['name'].'" ';
      if (isset($array['onchange'])) $output.='onChange="'.$array['onchange'].'" ';
      $output.=">\n";

      foreach($array['option'] as $key => $option)
      {

      	if (isset($array['value'][$key]))
      	{
	      	if ($array['selected'] && $array['selected'] == trim($array['value'][$key]))
	      		$selected = 'selected';
	      	else
	      		$selected = '';

      		$output .= '<option value="'.$array['value'][$key].'" '.$selected.'>'.$option."</option>\n";
      	}
      	else
      	{
	      	if ($array['selected'] && $array['selected'] == trim($array['option'][$key]))
	      		$selected = 'selected';
	      	else
	      		$selected = '';

      		$output .= '<option '.$selected.'>'.$option."</option>\n";
      	}
      }

      $output .= "</select>";
      if ($echo == false) {
         return $output;
      } else {
         echo $output;
      }
   }

	/**
	 * displayMessage
	 *
	 * @access public
	 * @param  string Type (info/warning/important/error)
	 * @param  string Text Message
	 * @return string HTML Output
 	 */
    function displayMessage($type='info',$text)
    {
    	if (strlen(trim($text))>0 || is_array($text)) {

	        if (is_array($text)) {
	    		//if (count($text)==0) return false;
                $message = '';
                foreach($text as $key => $value) {
                        $message .= $value.'<br>';
                }
                $text = $message;
        	}

	        switch($type)
	        {
	            case 'error':
	                $output = '<p class="alert">'.$text.'</p>';
	                break;
	            case 'information':
	            case 'info':
	                $output = '<p class="info">'.$text.'</p>';
	                break;
	            case 'important':
	            case 'warning':
	                $output = '<p class="warning">'.$text.'</p>';
	                break;
	            case 'ok':
	            case 'success':
	                $output = '<p class="success">'.$text.'</p>';
	                break;
	        }
	        return $output;
    	}
		return false;
    }


  	/**
	 * Return Error Messages as a String
	 *
	 * @access public
	 * @var object Class Object
	 */
	function getErrorMessages($classObject){
		if(is_array($classObject->error_messages)){
			foreach($classObject->error_messages as $i => $msg){
				$errors .= "$msg<br>";
			}
		}

		return $errors;
	}

	function popup($echo_output = false)
	{
		$javascript = "<SCRIPT LANGUAGE=\"JavaScript\">
		<!-- //Begin
		function popup(page,w,h,scroll,menubars,toolbars,resize,location) {
			var winl = (screen.width - w) / 2;
			var wint = (screen.height - h) / 2;
			windowprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',location='+location+',scrollbars='
			+ scroll + ',menubars='+menubars+',toolbars='+toolbars+',resizable='+resize;
			win = window.open(page, '_blank', windowprops);
			if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
		}
		//  End -->
		</script>\n";

		if ($echo_output) echo $javascript;
		return $javascript;
	}

	/**
	 * Function that convert all applicable characters to HTML entities, but html tags.
	 *
	 * @access public
	 * @param string 	Unparsed HTML string.
	 * @return string 	Parsed and converted HTML string
	 */
	function htmlEncodeText ($string)
	{
		$pattern = '<([a-zA-Z0-9\.\, "\'_\/\-\+~=;:\(\)?&#%![\]@]+)>';
		preg_match_all ('/' . $pattern . '/', $string, $tagMatches, PREG_SET_ORDER);
		$textMatches = preg_split ('/' . $pattern . '/', $string);

		$str = "";
		foreach ($textMatches as $key => $value) {
			$str .= htmlentities ($value) . $tagMatches[$key][0];
		}
		return $str;
	}

	function escapeOutput($string) {
		return htmlentities($string,ENT_QUOTES,'UTF-8');
	}

	/**
	 * Check if a column is registered in the error_objects array, if true return CSS format to display
	 *
	 * @param string $object
	 * @param array $error_objects
	 * @return string Style on success, FALSE on error
	 */
	public function isErrorObject($object, $error_objects) {
		if (is_array($error_objects)) {
			if (in_array($object, $error_objects)) {
				return 'background: #f47920; color: #ffffff;';
			}
		}
		return false;
	}

	/**
	 * Creates a multipage navigation in HTML
	 *
	 * Example:
	 * <code>
	 * $page			= $_GET['page'];
	 * $photo_count 	= $obj_photos->getPhotoCount($user_id);
	 * $max_displayed   = 6;
	 * $url				= "/{$_GET['u']}/photos?size={$size}&page=%d";
	 *
	 * $obj_tpl->setVar(array(
	 *		'VAR_PAGE_NAVIGATION'	=> $obj_html->pageNavigator($url,$page,$photo_count,$max_displayed,"Viewing %d-%d of %d photos"),
	 * ));
	 * </code>
	 *
	 * @param string $url - The URL used to get to next/prev page. Format: "/mypage?page=%d" becomes "/mypage?page=3"
	 * @param integer $page - Current page (nr) being accessed (displayed)
	 * @param integer $element_count - How many elements in total are available
	 * @param integer $max_displayed - How many elements should be viewable per single page
	 * @param string $summary - String in the following format: "Listing %d-%d of %d" becomes "Listing 11-20 of 33"
	 * @return string Ready to use HTML code of the page navigator
	 */
	function pageNavigator($url,$page,$element_count,$max_displayed=10,$summary=false) {
		$last_page = roundup(($element_count/$max_displayed),0);
		if ($element_count > $max_displayed) {
			$content = '<div id="page-nav" style="float:right;margin: 0px 10px;"><ul class="page-nav-menu">';

			// Check if current page is more than 5 page, if so display middle section and link to first page
			if ($page >= 4) {
				$content.= '<li><a href="'.sprintf($url,1).'" class="'.(($page==1)?'page-nav-active':'').'">1</a></li>';
				$content.= '<li style="width:30px;text-align:center;"> ... </li>';
			}
			if ($page>=4) {
				$page_nav_1_mod=($page-3);
				$page_nav_2_mod=($page-3);
				$page_nav_3_mod=($page-3);
			} else {
				$page_nav_1_mod=0;
				$page_nav_2_mod=0;
				$page_nav_3_mod=0;
			}
			$content.= '<li><a href="'.sprintf($url,(1+$page_nav_1_mod)).'" class="'.(($page==(1+$page_nav_1_mod))?'page-nav-active':'').'">'.(1+$page_nav_1_mod).'</a></li>';
			$content.= '<li><a href="'.sprintf($url,(2+$page_nav_2_mod)).'" class="'.(($page==(2+$page_nav_2_mod))?'page-nav-active':'').'">'.(2+$page_nav_2_mod).'</a></li>';

			// Check if there are more than 2 pages, if so, display third page
			if ($element_count > ($max_displayed*2)) {
				$content.= '<li><a href="'.sprintf($url,(3+$page_nav_3_mod)).'" class="'.(($page==(3+$page_nav_3_mod))?'page-nav-active':'').'">'.(3+$page_nav_3_mod).'</a></li>';
			}

			// Check if current page is more than 1 and last page is more than 3
			if ( ($element_count > ($max_displayed*2)) && $page > 1 && $last_page>3) {
				if ($page==2) {
					$page_nav_4_mod=2;
				} else {
					$page_nav_4_mod=1;
				}
				if ($page <= ($last_page-1) || $page < 4) {
					$content.= '<li><a href="'.sprintf($url,($page+$page_nav_4_mod)).'">'.($page+$page_nav_4_mod).'</a></li>';
				}
			}
			// Check if current page is more than 2 and last page is more than 4
			if ( ($element_count > ($max_displayed*2)) && $page > 2 && $last_page>4) {
				if ($page==3) {
					$page_nav_4_mod=3;
				} else {
					$page_nav_4_mod=2;
				}
				if ($page <= ($last_page-2) || $page < 4) {
					$content.= '<li><a href="'.sprintf($url,($page+2)).'">'.($page+2).'</a></li>';
				}
			}
			// Check if there are more than 3 pages, if so, display middle section and link to last page
			if ( ($element_count > ($max_displayed*3)) && ($page<>3 || $last_page<>5)) {
				if ($page <= ($last_page-4) || $page < 4) {
					$content.= '<li style="width:30px;text-align:center;"> ... </li>';
				}
				if ($page <= ($last_page-3) || $page < 4) {
					$content.= '<li><a href="'.sprintf($url,$last_page).'" class="'.(($page==$last_page)?'page-nav-active':'').'">'.$last_page.'</a></li>';
				}
			}
			$from_photo = (($page-1)*$max_displayed)+1;
			$to_photo 	= (($max_displayed*$page)>$element_count)?$element_count:($max_displayed*$page);
			$content.='</div><div style="clear: both;"></div>';
			if ($summary) {
				$content .= '<p align="left" style="position:relative;margin:-20px 20px 0px 0px;font-size:14px;color:#cccccc;float:left;width:400px;">'.sprintf($summary,$from_photo,$to_photo,$element_count).'</p>';
			}
		}
		return $content;
	}

	/**
	 * Composes a breadcrumb to uses as a navigation for hierarchy page structure
	 *
	 * @param array $name_url_pair - array where key is the name and value the url
	 * @return string
	 */
	function composeBreadcrumb($name_url_pair) {
		$crumb_tpl = '<a href="%s">%s</a>';

		$result = array();
		foreach ($name_url_pair as $key => $value) {
			$result[] = sprintf($crumb_tpl, $value, $key);
		}

		return implode(' &raquo; ', $result);
	}
}
?>
